/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

#include "common/lang/comparator.h"
#include "common/log/log.h"
#include "common/type/char_type.h"
#include "common/type/attr_type.h"
#include "common/type/data_type.h"
#include "common/value.h"
#include <string>



int CharType::compare(const Value &left, const Value &right) const
{
  //默认左边一定这是当前类型
  ASSERT(left.attr_type() == AttrType::CHARS, "invalid type");
  ASSERT(right.attr_type() == AttrType::CHARS || right.attr_type() == AttrType::DATES, "invalid type");
  std::string left_string_value = left.get_string();
  std::string right_string_value = right.get_string();
  return common::compare_string(
      (void *)left.value_.pointer_value_, left.length_, (void *)right.value_.pointer_value_, right.length_);
}


int CharType::compare_like(const Value &left, const Value &right) const
{
  //当前仅支持char类型的like
  ASSERT(left.attr_type() == AttrType::CHARS && right.attr_type() == AttrType::CHARS, "invalid type");
  std::string left_string_value = left.get_string();
  std::string right_string_value = right.get_string();
  return common::compare_string_like(
      (void *)left.value_.pointer_value_, left.length_, (void *)right.value_.pointer_value_, right.length_);
}


RC CharType::set_value_from_str(Value &val, const string &data) const
{
  val.set_string(data.c_str());
  return RC::SUCCESS;
}

RC CharType::cast_to(const Value &val, AttrType type, Value &result) const
{
  switch (type) {
    case AttrType::DATES:{
      std::string s = val.get_string();
      //调用data实例的函数
       return type_instance(AttrType::DATES)->set_value_from_str(result, val.value_.pointer_value_);
    }break;
    case AttrType::VECTORS:{
      std::string s = val.get_string();
      //调用data实例的函数
       return type_instance(AttrType::VECTORS)->set_value_from_str(result, val.value_.pointer_value_);
    }break;
    default: return RC::UNIMPLEMENTED;
  }
  return RC::SUCCESS;
}

int CharType::cast_cost(AttrType type)
{
  if (type == AttrType::CHARS) {
    return 0;
  }else {
    return 1;
  }
  return INT32_MAX;
}

RC CharType::to_string(const Value &val, string &result) const
{
  stringstream ss;
  ss << val.value_.pointer_value_;
  result = ss.str();
  return RC::SUCCESS;
}